package ru.lukyanets.transmission.protocol;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import ru.lukyanets.transmission.protocol.client.RpcClient;
import ru.lukyanets.transmission.protocol.client.builder.HostInfo;
import ru.lukyanets.transmission.protocol.client.builder.RestRpcClientBuilder;
import ru.lukyanets.transmission.protocol.client.exception.TransmissionException;
import ru.lukyanets.transmission.protocol.model.session.Session;
import ru.lukyanets.transmission.protocol.model.session.stats.SessionStats;
import ru.lukyanets.transmission.protocol.model.torrent.Torrent;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;

/**
 * @author slukyanets
 */
@Disabled
public class TorrentTest {
    private RpcClient rpcClient;

    @BeforeEach
    public void init(){
        RestRpcClientBuilder builder = new RestRpcClientBuilder();

        rpcClient = builder.host(new HostInfo("localhost", 9091)).build();
    }

    @Test
    public void testGetTorrents() throws Exception {
        List<Torrent> torrents = rpcClient.getTorrents();
        for(Torrent torrent : torrents) {
            System.out.println(torrent.getId() + " - " + torrent.getName());
        }
    }

    @Test
    public void testGetSession() throws Exception {
        Session session = rpcClient.getSession();
        System.out.println(session.getDownloadDir());
    }

    @Test
    public void testGetTorrent() throws Exception {
        Torrent torrent = rpcClient.getTorrent(1);
        System.out.println(torrent.getName());
    }

    @Test
    public void testPort() throws Exception {
        boolean isOpen = rpcClient.testPort();
        System.out.println(isOpen);
    }

    @Test
    public void testGetSessionStats() throws Exception {
        SessionStats stats = rpcClient.getSessionStats();
        System.out.println(stats.getTorrentCount());
    }

    @Test
    public void testAddTorrent() throws IOException, TransmissionException {
        InputStream input = getClass().getClassLoader().getResourceAsStream("test.torrent");
        int bufferSize = 4096;

        StringBuilder builder = new StringBuilder(bufferSize);
        byte[] buffer = new byte[bufferSize];
        assert input != null;
        while (input.read(buffer, 0, bufferSize) >= 0) {
            builder.append(Base64.getEncoder().encodeToString(buffer));
        }
        input.close();

        int id = rpcClient.addTorrent(builder.toString(), null, null, null, true, 0, 0);
        System.out.println(id);
    }
}
